/* Author: Nahuel F. Lema, Maxi Yañez
 */

var homeController = {

    windowResize: {
        bind: function(){
            var w = $(window), ww = w.width();
            if (ww < 767) homeController.mobileMethods.init();

            if (ww > 768) homeController.facebookComponent.init();

            if (ww > 768) homeController.tweeterComponent.init();

            w.resize(function(){
                if (w.width() < 767) homeController.mobileMethods.init();
            });
        },

        init: function(){
            this.bind();
        }
    },

    mobileMethods: {

        collapseContent: {
            defs: {
                active: false,
                collapsives: '',
                expanded: ['filtros-container']
            },

            expandDefaults: function(){
                var collapsives = this.defs.collapsives,
                expanded = this.defs.expanded,
                container = '', item = '';

                for (var x = 0, l = collapsives.length; x < l; x++) {
                    item = $(collapsives[x]);
                    container = item.parents('.box-container');

                    for (var y = 0, t = expanded.length; y < t; y++) {
                        if (container.attr('id') == expanded[y]) {
                            item.addClass('section-collapse-active');
                            container.find('.icons-collapse').removeClass('icon-collapse-down').addClass('icon-collapse-up');
                        }
                    }
                }

                collapsives = expanded = container = item = x = y = l = t = null;
            },

            expand: function(el){
                var container = el.parents('.box-container'),
                collapse = container.find('.icons-collapse'),
                sectionCollapse = container.find('.section-collapse');

                if (!!container.find('.icon-collapse-down').length) {
                    sectionCollapse.addClass('section-collapse-active');
                    collapse.removeClass('icon-collapse-down').addClass('icon-collapse-up');
                } else {
                    sectionCollapse.removeClass('section-collapse-active');
                    collapse.removeClass('icon-collapse-up').addClass('icon-collapse-down');
                }

                if (container.attr('id') == 'facebook-container' && !!homeController.facebookComponent)
                    homeController.facebookComponent.init();

                if (container.attr('id') == 'twitter-container' && !!homeController.tweeterComponent)
                    homeController.tweeterComponent.init();
            },

            bind: function(){
                var self = this, el;

                $('.box-header').die('click').live('click', function(e){
                    e.preventDefault();
                    el = $(this).find('.btn-collapse');
                    if (el.length) self.expand(el);
                });
            },

            init: function(){
                this.defs.active = true;
                this.defs.collapsives = $(js.get.item('.section-collapse'));
                this.expandDefaults();
                this.bind();
            }
        },

        init: function(){
            if (!this.collapseContent.defs.active) this.collapseContent.init();
        }
    },

    flexSliderComponent: {

        get: function(){
            var componentsPath = scriptsController.defs.baseUrl + scriptsController.defs.componentsPath + 'flexslider/',
            self = this;

            scriptsController.loadCss('flexslider/flexslider.min.css');

            $.getScript(componentsPath + 'jquery.flexslider-min.js', function(){
                self.bind();
            });
        },

        bind: function(){
            $(js.get.item('.flexslider')).flexslider({
                animation: "slide"
            });
            homeController.flexSliderComponent = null;
        },

        init: function(){
            if (!!js.get.item('.flexslider')[0]) this.get();
        }
    },

    carouselComponent: {
        bind: function(){
            $('.carousel').carousel({
                interval: 5000,
                cycle: 'cycle'
            });
        },
        init: function(){
            this.bind();
        }
    },

    facebookComponent: {
        defs: {
            loaded: false,
            container: js.get.item('#facebook-container')[0]
        },

        load: function(){
            var self = this;

            !function(d, s, id) {
                var js, fjs = d.getElementsByTagName(s)[0],
                frame = '<iframe src="//www.facebook.com/plugins/likebox.php?locale=es_ES&href=http%3A%2F%2Fwww.facebook.com%2FDondeReciclo&amp;width=100&amp;height=674&amp;colorscheme=light&amp;show_faces=true&amp;border_color=%23CCC&amp;stream=true&amp;header=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100%; height:674px; background: #fff;" allowTransparency="true"></iframe>';
                if (d.getElementById(id)) return;
                js = d.createElement(s);
                js.id = id;
                js.src = "//connect.facebook.net/es_ES/all.js#xfbml=1";
                fjs.parentNode.insertBefore(js, fjs);
                $(self.defs.container).find('.box-list').append(frame);
                scriptsController.loader.remove($(self.defs.container).find('.section-content'));
                self.defs.loaded = true;
                homeController.facebookComponent = null;
            }(document, 'script', 'facebook-jssdk');
        },

        init: function(){
            if (!this.defs.loaded) {
                scriptsController.loader.append($(this.defs.container).find('section-content'), 'medium');
                this.load();
            }
        }
    },

    tweeterComponent: {
        defs: {
            loaded: false,
            container: js.get.item('#twitter-container')[0],
            list: $(js.get.item('#twitter-container')[0]).find('.box-list'),
            tpl: js.escape.decode(js.get.item('#tpl-tweeter')[0].innerHTML),
            user: 'dondereciclo_ar',
            numTweets: 3
        },

        load: function(){
            var self = this;

            !function(d,s,id){
                var js,fjs=d.getElementsByTagName(s)[0];
                if(!d.getElementById(id)){
                    js=d.createElement(s);
                    js.id=id;
                    js.src="https://platform.twitter.com/widgets.js";
                    fjs.parentNode.insertBefore(js,fjs);

                    self.loadTweets();
                    self.defs.loaded = true;
                    scriptsController.loader.remove($(self.defs.container).find('.section-content'));
                }
            }(document,"script","twitter-wjs");
        },

        loadTweets: function() {
            var self = this, items = '';

            $.ajax({
                url: 'http://api.twitter.com/1/statuses/user_timeline.json/',
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    screen_name: self.defs.user,
                    include_rts: true,
                    count: self.defs.numTweets,
                    include_entities: true
                },
                success: function(data, textStatus, xhr) {
                    for (var i = 0, l = data.length; i < l; i++) {
                        items += self.defs.tpl
                        .replace('${TWEET_TEXT}', self.ify.clean(data[i].text))
                        .replace('${USER}', '@' + data[i].user.screen_name);
                    }
                    self.defs.list.html(items);

                    homeController.tweeterComponent = null;
                }
            });
        },

        ify: {
            link: function(tweet) {
                return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
                    var http = m2.match(/w/) ? 'http://' : '';
                    return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
                });
            },
            at: function(tweet) {
                return tweet.replace(/\B[@＠]([a-zA-Z0-9_]{1,20})/g, function(m, username) {
                    return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>';
                });
            },
            list: function(tweet) {
                return tweet.replace(/\B[@＠]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) {
                    return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/' + userlist + '">@' + userlist + '</a>';
                });
            },
            hash: function(tweet) {
                return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) {
                    return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>';
                });
            },
            clean: function(tweet) {
                return this.hash(this.at(this.list(this.link(tweet))));
            }
        },

        init: function(){
            if (!this.defs.loaded) {
                scriptsController.loader.append($(this.defs.container).find('.section-content'), 'medium');
                this.load();
            }
        }
    },

    getTotalMarkers: {
        load: function(){
            var self = this;

            $.ajax({
                url: scriptsController.defs.baseUrl + 'controllers/markerController/total/',
                type: 'GET',
                success: function(data) {
                    self.print(data);
                }
            });
        },

        print: function(t){
            js.get.item('.btn-pts-green .center .val')[0].innerHTML = t;
        },

        init: function(){
            this.load();
        }
    },

    validate: {

        get: function(){
            var componentsPath = scriptsController.defs.baseUrl + scriptsController.defs.componentsPath + 'jvalidation/',
            self = this;

            $.getScript(componentsPath + 'jquery.validate.min.1.9.js', function(){
                self.bind();
            });
        },

        bind: function(){
            var form = $(js.get.item('#newsletter-banner .form')[0]);
            $(js.get.item('#newsletter-banner .btn-green')[0]).click(function(e){
                e.preventDefault();
                form.submit();
            });

            form.validate({
                rules: {
                    'email-field' : {
                        required : true,
                        email	 : true
                    }
                },
                messages: {
                    'email-field' : {
                        required : "Este campo es requerido",
                        email	 : "Debe ser un email"
                    }
                },
                submitHandler: function() {
                    scriptsController.fixedLoader.show();
                    $.ajax({
                        type:'post',
                        url:scriptsController.defs.baseUrl+'controllers/newsletterController/save',
                        data:'email='+$('#email-field').val(),
                        success: function () {
                           scriptsController.fixedLoader.hide();
                           $('#newsletterModal').modal('show');
                           $('#email-field').val('');
                        }
                   })
                }
            });
        },

        init: function(){
            this.get();
        }
    },

    blog: {
        defs: {
            cuantos: 3,
            destino: document.getElementById('listadoPosts'),
            imageSize: {
                ancho:160,
                alto:120
            }
        },
        init: function () {
            var self = this;
            $.ajax({
                url:scriptsController.defs.baseUrl+'resources/blog/php/controllers/listarPosts.controller.php',
                type:'post',
                data:'cuantos='+self.defs.cuantos,
                success:function (data) {
                    self.defs.destino.innerHTML = data;
                    scriptsController.loader.remove($(self.defs.destino));
                    $.getScript(scriptsController.defs.baseUrl+'resources/js/imagesFrame.js', function(){
                        self.bind();
                    });
                }
            })
        },
        bind: function () {
            var self = this;
            if (!$('.imagesFrame').size()) {
                //ImagesFrame.create(self.defs.imageSize.ancho, self.defs.imageSize.alto, $('#listadoPosts img'), true);
                setTimeout(200, self.bind)
            } else {
                $('#listadoPosts img').load(function () {
                    ImagesFrame.create(self.defs.imageSize.ancho, self.defs.imageSize.alto, $(this), true);
                })
            }
        }
    },

    flexSlider: {
        defs: {
            loaded: false,
            container: '',
            styleTag: '<link type="text/css" rel="stylesheet" href="'+ scriptsController.defs.baseUrl + 'resources/jquery/components/flexslider/flexslider.css"/>',
            scriptTag: '<script type="text/javascript" src="'+ scriptsController.defs.baseUrl + 'resources/jquery/components/flexslider/jquery.flexslider-min.js"></script>'
        },

        load: function(){
            var self = this,
            head = $('head');
            head.append(self.defs.styleTag, self.defs.scriptTag);
            //            $.getScript(scriptsController.defs.baseUrl + 'resources/jquery/components/flexslider/jquery.flexslider-min.js', function(){
            homeController.yoReutilizo.init();
            homeController.vimeo.init();
        //            });
        },

        init: function(){
            this.load();
        }
    },

    yoReutilizo: {
        get: function(){
            var self = this;
            $.ajax({
                url: scriptsController.defs.baseUrl+'controllers/yoreuso/getSeleccion',
                dataType:'json',
                success:function (data) {
                    var result = [], repetidos='', n=0, i=0;
                    data = data.reusos;
                    while(i<3) {
                        n = Math.floor(Math.random()*data.length);
                        if (repetidos.indexOf('{'+n+'}') == -1) {
                            result.push(data[n]);
                            repetidos += '{'+n+'}';
                            i++;
                        }
                    }
                    //items[Math.floor(Math.random()*items.length)]
                    self.print(result);
                }
            })
        },

        print: function(items){
            var tpl = $('#tpl-yo-reutilizo').val(), item,
            itemsTpl = '', container = $('#yo-reutilizo-container .flexslider');
        
            for (var x = 0, l = items.length; x < l; x++) {
                item = items[x];
                itemsTpl += tpl
                .replace(/\$\{id}/g, parseInt(item.id))
                .replace(/\$\{path}/g, scriptsController.defs.baseUrl + 'yoReutilizo')
                .replace(/\$\{titulo\}/g, item.titulo)
                .replace(/\$\{texto}/g, item.bajada)
                .replace(/\$\{img}/g, scriptsController.defs.baseUrl + 'content/yoreuso/seleccion/' + item.imagen)
                .replace(/\$\{[a-z]+\}/g, '');
            }

            container.find('.slides').append(itemsTpl);

            container.flexslider({
                animation: "slide"
            });
        },

        init: function(){
            this.get();
        }
    },

    vimeo: {
        get: function(){
            var self = this;            
            $.ajax({
                url:'http://vimeo.com/api/v2/dondereciclo/videos.json',
                jsonp: 'callback',
                dataType: "jsonp",
                success:function (data) {
                    self.print(data);
                }
            })
        },

        print: function(items){
            var tpl = $('#tpl-vimeo').val(), item,
            itemsTpl = '', container = $('#vimeo-container .flexslider');
            for (var x = 0, l = items.length; x < l; x++) {
                item = items[x];
                itemsTpl += tpl
                .replace(/\$\{id}/g, parseInt(item.id))
                .replace(/\$\{url}/g, item.url)
                .replace(/\$\{thumbnail}/g, item.thumbnail_large)
                .replace(/\$\{title}/g, item.title)
                .replace(/\$\{[a-z]+\}/g, '');
            }

            container.find('.slides').append(itemsTpl);

            container.flexslider({
                animation: "slide"
            });
        },

        init: function(){
            this.get();
        }
    },

    init: function(){
        this.windowResize.init();

        //	this.flexSliderComponent.init();
        this.carouselComponent.init();

        this.getTotalMarkers.init();

        this.validate.init();

        this.blog.init();

        this.flexSlider.init();
    }
}

homeController.init();